// page/component/new-pages/cart/cart.js
const app = getApp();
// 引入api.js文件
const api = require('../../utils/api');

const { myRequest } = require('../../utils/myRequest');

Page({
    data: {
        cart:null,
        carts: [],               // 购物车列表
        hasList: false,          // 列表是否有数据
        totalPrice: 0,           // 总价，初始为0
        selectAllStatus: true,    // 全选状态，默认全选
        obj: {
            name: "hello"
        },
        cartsSelect:[],          //选中的产品数组
        productIds:null,
        isChecked:true,
    },
    
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // let id = options.id;
        // let pnum = Number(options.num);
        // console.log(pnum)
        
    },

    // 请求数据

    onShow() {
        // 获取并保存数据
        // this.setData({
        //     hasList: true,
        //     carts: [
        //         { 
        //             id: 1,
        //             title: '去年的表',
        //             image: '../../images/5355.jpg',
        //             num: 4,
        //             price: 30,
        //             selected: true
        //         },
        //         { 
        //             id: 2,
        //             title: '今年的表',
        //             image: '../../images/5355.jpg',
        //             num: 1,
        //             price: 20,
        //             selected: true
        //         }
        //     ]
        // });

      myRequest({
        url: api.cartIndex,
        data: {

        },
        method: 'get',
        success: (res) => {
          let that = this;
          console.log('数据', res);
          let a = res.data.data.cartList;

          a.forEach(function (item, index) {
            let obj = new Object();
            obj.id = item.goods_id;
            obj.title = item.goods_name;
            obj.image = item.list_pic_url;
            obj.num = item.number;
            obj.price = item.retail_price;
            obj.selected = true;
            obj.productId = item.product_id;
            obj.cid = item.id
            for(let x = 0; x < that.data.carts.length;x++){
              if(that.data.carts[x].productId == obj.productId){
                return false;
              }
            }
            that.data.carts = that.data.carts.concat(obj);
          })
          console.log(this.data.carts);
          this.setData({
            carts: this.data.carts
          })
          if (this.data.carts.length != 0) {
            this.setData({
              hasList: true,
            })
          }
          this.getTotalPrice();
        }
      })

        
        
    },
    /**
     * 当前商品选中事件
     */
    selectList(e) {
        //保存该点击元素的下标
        const index = e.currentTarget.dataset.index;
        //获取数据
        let carts = this.data.carts;
        //获取数据的对应的条目的selected属性
        const selected = carts[index].selected;
        // 改变selected的boolean值
        carts[index].selected = !selected;
        //重新获取数据
        this.setData({
            carts: carts
        });
        this.getTotalPrice();
    },

    /**
     * 删除购物车当前商品
     */
    deleteList(e) {
        //保存该点击元素的下标
        const index = e.currentTarget.dataset.index;
        let carts = this.data.carts;
        //把对应的数据条目删除
        let id = String(carts[index].productId)
        myRequest({
          url: api.cartDelete,
          data: {
            productIds: id
          },
          method: 'get',
          success: (res) => {
            console.log(res)
            if (res.data.errmsg=="删除出错"){
              wx.showToast({
                title: '删除出错',
                icon:'none',
                duration:2000,
              })
              return false;
            }
            carts.splice(index, 1);

            this.setData({
              carts: carts
            });
          }
        })
        //如果数据为空，把hasList 设置为false不显示内容
        if (!carts.length) {
            this.setData({
                hasList: false
            });
        } else {
            this.getTotalPrice();
        }
    },

    /**
     * 购物车全选事件
     */
    selectAll(e) {
        //点击改变全选值
        let selectAllStatus = this.data.selectAllStatus;
        selectAllStatus = !selectAllStatus;

        let carts = this.data.carts;

        //遍历数组，把产品选项全都改为和全选一样的值
        for (let i = 0; i < carts.length; i++) {
            carts[i].selected = selectAllStatus;
        }
        //更新数据
        this.setData({
            selectAllStatus: selectAllStatus,
            carts: carts
        });
        this.getTotalPrice();
    },

    /**
     * 绑定加数量事件
     */
    addCount(e) {
        //获取点击时的元素绑定的下标
        const index = e.currentTarget.dataset.index;
        let carts = this.data.carts;
        //把数据内容的值，先保存，经过加减，再赋值
        let num = carts[index].num;
        num = num + 1;
        carts[index].num = num;
        //更新数据
      myRequest({
        url: api.cartUpdate,
        data: {
          id: carts[index].cid,
          goodsId: carts[index].id,
          number: carts[index].num,
          productId: carts[index].productId
        },
        method: 'post',
        success: (res) => {
          this.setData({
            carts: carts
          });
          this.getTotalPrice();
        }
      })
        
    },

    /**
     * 绑定减数量事件
     */
    minusCount(e) {
        const index = e.currentTarget.dataset.index;
        const obj = e.currentTarget.dataset.obj;
        let carts = this.data.carts;
        //判断如果小于1直接跳出，不做任何操作
        let num = carts[index].num;
        if (num <= 1) {
            return false;
        }
        num = num - 1;
        carts[index].num = num;
      myRequest({
        url: api.cartUpdate,
        data: {
          id: carts[index].cid,
          goodsId: carts[index].id,
          number: carts[index].num,
          productId: carts[index].productId
        },
        method: 'post',
        success: (res) => {
          this.setData({
            carts: carts
          });
          this.getTotalPrice();
        }
      })
    },

    /**
     * 计算总价
     */
    getTotalPrice() {
        let carts = this.data.carts;                  // 获取购物车列表
        let total = 0;
        for (let i = 0; i < carts.length; i++) {         // 循环列表得到每个数据
            if (carts[i].selected) {                     // 判断选中才会计算价格
                total += carts[i].num * carts[i].price;   // 所有价格加起来
            }
        }
        this.setData({                                // 最后赋值到data中渲染到页面
            carts: carts,
            totalPrice: total.toFixed(2)
        });
    },

    //设置跳转带参数形式
    toOrder(){
        //遍历已经选中的产品，然后添加到一个数组里
        let cartsSelect = this.data.cartsSelect;
        let carts = this.data.carts;
        for(let i=0;i<carts.length;i++){
            if(carts[i].selected==true){
                cartsSelect.push(carts[i]);
            }
        }
        this.setData({
            cartsSelect:cartsSelect
        })
        wx.redirectTo({
            url: '../order/order',
        });
        app.globalData.cartsSelect=cartsSelect;
        app.globalData.totalPrice = this.data.totalPrice;

        console.log('123')
        console.log('cartsSelect',cartsSelect);
    }

})